import cv2
import threading
import time
import xf_color
import numpy as np
import socket


class Producer(threading.Thread):
    def __init__(self, rtmp_str):
        super(Producer, self).__init__()
        self.rtmp_str = rtmp_str
        # 通过cv2中的类获取视频流操作对象cap
        self.cap = cv2.VideoCapture(self.rtmp_str)
        # 调用cv2方法获取cap的视频帧（帧：每秒多少张图片）
        self.fps = self.cap.get(cv2.CAP_PROP_FPS)
        print(self.fps)

        # # 获取cap视频流的每帧大小
        # self.width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        # self.height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        # self.size = (self.width, self.height)
        # print(self.size)

        # 定义编码格式mpge-4
        self.fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', '2')

        # 定义视频文件输入对象
        # Vself.outVideo = cv2.VideoWriter('test.mp4', self.fourcc, self.fps, self.size)


    def detect(self):
        # 对视频或摄像头获取的影像目标区域颜色进行识别
        cap = self.cap
        # cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1100)  # 这里窗口大小调节只对摄像头有效
        # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 750)

        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host = "192.168.43.65"

        port = 12346

        # 连接服务端

        client.connect((host, port))

        while cap.isOpened():
            ret, frame0 = cap.read()
            if ret is not True:
                continue
            # 对图像帧进行翻转（因为opencv图像和我们正常是反着的） 视频是正常的，摄像头是反转的
            # frame0 = cv2.flip(src=frame0, flipCode=2)

            # frame = frame[180:280, 180:380] # [y:y+h, x:x+w]
            # frame = frame0[200:400, 100:300] # 设置检测颜色的区域，四个顶点坐标
            frame = frame0

            # frame=cv2.resize(src=frame,dsize=(750,600))
            #hsv_frame = cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2HSV)
            # 获取读取的帧的高宽
            height, width, channel = frame.shape
            color,point1,point2 = xf_color.get_color(frame)

            # 绘制文本
            cv2.putText(frame, color, (5, 50), cv2.FONT_HERSHEY_COMPLEX, 0.75, (0, 0, 255), 2)
            cv2.rectangle(frame, point1, point2, color=(255, 0, 0), thickness=10)

            cv2.imshow('frame', frame)
            cv2.waitKey(1)



            send_msg = color
            # 发送数据，编码
            client.send(send_msg.encode("utf-8"))
            # 接收服务端返回的数据
            msg = client.recv(1024)
            # 解码
            print("接收：%s" % msg.decode("utf-8"))

            # 关闭客户端
        client.close()
        cap.release()
        cv2.destroyAllWindows()


if __name__ == '__main__':
    print('run project')
    rtmp_str = "rtmp://192.168.43.65/live"

    producer = Producer(rtmp_str)
    producer.detect()




